//
//  SegmentView.swift
//  SwiftUI_App
//
//  Created by qingzhou on 2021/6/22.
//

import SwiftUI

struct SegmentView: View {
    var segments: [String]
    @State var currentTab: String
    
    @Namespace var animation
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false, content: {
            HStack (spacing:0){
                ForEach(segments, id:\.self) {item in
                    TabButton(title: item, currentTab: $currentTab, animation: animation)
                }
            }
        })
        .background(Color.white)
    }
}

struct TabButton:View {
    var title: String
    @Binding var currentTab: String
    var animation: Namespace.ID
    var body: some View {
        Button(action:{
            withAnimation{
                currentTab = title
            }
        }){
            LazyVStack(spacing: 10) {
                Text(title)
//                    .fontWeight(.semibold)
                    .foregroundColor(currentTab == title ? .blue : .gray)
                    
                    
                if currentTab == title {
                    Capsule()
                        .foregroundColor(.blue)
                        .frame(height:  1.2)
                        .matchedGeometryEffect(id: "TAB", in: animation)
                } else {
                    Capsule()
                        .foregroundColor(.clear)
                        .frame(height:  1.2)
                    
                }
                
            }
            .padding(.horizontal,10)
        }
    }
}

struct SegmentView_Previews: PreviewProvider {
    static var previews: some View {
        SegmentView(segments: ["直播","推荐","热门","追番","影视","建党百年"], currentTab: "15")
    }
}
